package org.micode.demo.web.controller;

import org.micode.common.domain.ApiResult;
import org.micode.common.domain.vo.KeyVO;
import org.micode.common.enums.ResultEnum;
import org.micode.common.exception.DataException;
import org.micode.common.helper.I18nMsgHelper;
import org.micode.demo.biz.vo.SysUserVO;
import org.micode.demo.db.vo.ChangePwdVO;
import org.micode.demo.web.service.UserService;
import org.micode.demo.web.base.BaseWebAdminController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户的Web控制类
 * <p>
 * author: wutianbin
 */
@RestController
@RequestMapping("/web-admin/user")
@Slf4j
public class UserController
        extends BaseWebAdminController {

    @Autowired
    private UserService userService;

    @PostMapping("/info")
    public ApiResult<SysUserVO> info(
            @RequestBody(required = false) KeyVO<Long> userKey) {
        log.debug(I18nMsgHelper.get("api.call.user.info") + " == {}", userKey);
        KeyVO<Long> theKey = new KeyVO<>(currentUserId());
        if (null != userKey && null != userKey.getKey()) {
            theKey.setKey(userKey.getKey());
        }

        if (null == theKey.getKey()) {
            throw new DataException(I18nMsgHelper.get("valid.user.not-userid"));
        }

        return invokeMethod(userService::info, theKey);
    }

    /**
     * 修改自己的登录密码
     */
    @PostMapping("/updateSelfPassword")
    public ApiResult<Integer> updateSelfPassword(
            @RequestBody ChangePwdVO pwdVO) {
        log.debug(I18nMsgHelper.get("api.call.user.updateSelfPassword") + " == {}", pwdVO);
        fillLoginFields(pwdVO);
        pwdVO.setUserId(currentUserId());
        pwdVO.verify();
        return invokeMethod(userService::updateLoginPassword, pwdVO,
                ResultEnum.REMOTE_ERROR, I18nMsgHelper.get("api.except.user.updateSelfPassword"));
    }

}
